package com.bigfans.userservice.api.clients;

import com.bigfans.Constants;
import com.bigfans.framework.utils.BeanUtils;
import com.bigfans.framework.web.CookieHolder;
import com.bigfans.framework.web.RestResponse;
import com.bigfans.userservice.model.Coupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class CouponServiceClient {

    @Autowired
    private RestTemplate restTemplate;

    public CompletableFuture<Coupon> getCoupon(String couponId) {
        String userToken = CookieHolder.getValue(Constants.TOKEN.KEY_NAME);
        return CompletableFuture.supplyAsync(() -> {
            HttpHeaders headers = new HttpHeaders();
            headers.put(Constants.TOKEN.HEADER_KEY_NAME, Arrays.asList(Constants.TOKEN.KEY_NAME + "=" + userToken));
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));

            UriComponents builder = UriComponentsBuilder.fromUriString("http://pricing-service/coupons/{id}").build().expand(couponId).encode();
            ResponseEntity<RestResponse> responseEntity = restTemplate.getForEntity(builder.toUri(), RestResponse.class);
            RestResponse response = responseEntity.getBody();
            Coupon coupon = BeanUtils.mapToModel((Map)response.getData() , Coupon.class);
            return coupon;
        });
    }
}
